package com.infinit.easyreader.framework;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.infinit.easyreader.R;
import com.infinit.easyreader.ui.FontActivity;
import com.infinit.easyreader.ui.ReaderActivity;
import com.infinit.easyreader.utils.Consts;

import java.util.Locale;

import app.minimize.com.seek_bar_compat.SeekBarCompat;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 类：com.infinit.easyreader.framework.SettingView V[1.0.0]
 * 作用：自定义的settingsView,用于处理阅读器的设置选项
 * Created by rzy on 2016/5/13.
 */
public class SettingView extends FrameLayout implements Consts, SeekBar.OnSeekBarChangeListener {

    public static final int FONT_REQUEST_CODE = 1;
    @Bind(R.id.sbSettingsBrightness)
    SeekBarCompat sbSettingsBrightness;
    @Bind(R.id.rbSysBrightness)
    RadioButton rbSysBrightness;
    @Bind(R.id.btFontDec)
    Button btFontDec;
    @Bind(R.id.tvFontSize)
    TextView tvFontSize;
    @Bind(R.id.btFontInc)
    Button btFontInc;
    @Bind(R.id.btFont)
    Button btFont;
    @Bind(R.id.ivBgYellow)
    CircleImageView ivBgYellow;
    @Bind(R.id.bgYellowChecked)
    Button bgYellowChecked;
    @Bind(R.id.ivBgblue)
    CircleImageView ivBgblue;
    @Bind(R.id.bgBlueChecked)
    Button bgBlueChecked;
    @Bind(R.id.ivBgGreen)
    CircleImageView ivBgGreen;
    @Bind(R.id.bgGreenChecked)
    Button bgGreenChecked;
    @Bind(R.id.ivBgWhite)
    CircleImageView ivBgWhite;
    @Bind(R.id.bgWhiteChecked)
    Button bgWhiteChecked;
    @Bind(R.id.ivBgBlack)
    CircleImageView ivBgBlack;
    @Bind(R.id.bgBlackChecked)
    Button bgBlackChecked;
    private int brightness;
    private int fontSize;
    private String fontFamily;
    private int bgPic;
    private Context context;
    private SharedPreferences preference;
    private SharedPreferences.Editor editor;
    private Activity mActivity;


    public SettingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.settings_layout, this);
        ButterKnife.bind(this);
        iniatate();
    }

    public SettingView(Context context) {
        this(context, null);
    }


    /**
     * 作用：获取SharedPreference中保存的信息
     */

    private void getIniatateInfo() {
        preference = context.getSharedPreferences(Consts.PREFERENCE_NAME, Context.MODE_PRIVATE);
        brightness = preference.getInt(SETTING_BRIGHTNESS, -1);
        fontSize = preference.getInt(SETTING_FONTSIZE, -1);
        fontFamily = preference.getString(SETTING_FONTFAMINY, "系统字体");
        bgPic = preference.getInt(SETTING_BG, -1);
    }


    /**
     * 初始化该View
     */


    private void iniatate() {
        getIniatateInfo();
        //设置亮度条
        if (brightness == -1) {
            rbSysBrightness.setChecked(true);
        } else {
            rbSysBrightness.setChecked(false);
            sbSettingsBrightness.setProgress(brightness);
        }
        sbSettingsBrightness.setEnabled(true);
        sbSettingsBrightness.setOnSeekBarChangeListener(this);
        //设置字体条
        tvFontSize.setText(fontSize == -1 ? String.valueOf(FONT_SIZE) : String.valueOf(fontSize));
        btFont.setText(fontFamily);
        //设置背景条
        if (bgPic != -1) {
            switch (bgPic) {
                case R.drawable.reader_bg_black:
                    checkSpcBg(ivBgBlack);
                    break;
                case R.drawable.reader_bg_lightblue:
                    checkSpcBg(ivBgblue);
                    break;
                case R.drawable.reader_bg_lightgreen:
                    checkSpcBg(ivBgGreen);
                    break;
                case R.drawable.reader_bg_white:
                    checkSpcBg(ivBgWhite);
                    break;
            }
        }


    }


    /**
     * 选中指定的背景图片，并且将设置保存在preference中
     * 将选中的颜色通过广播发送出去
     */


    private void checkSpcBg(ImageView ivClicked) {
        if (editor == null) {
            editor = preference.edit();
        }
        getCurrentActivity();
        bgBlueChecked.setVisibility(GONE);
        bgGreenChecked.setVisibility(View.GONE);
        bgWhiteChecked.setVisibility(View.GONE);
        bgYellowChecked.setVisibility(View.GONE);
        bgBlackChecked.setVisibility(View.GONE);
        int clickedId = ivClicked.getId();
        Intent intent = new Intent();
        intent.setAction(ReaderActivity.SET_BG);
        switch (clickedId) {
            case R.id.ivBgBlack:
                bgBlackChecked.setVisibility(View.VISIBLE);
                editor.putInt(SETTING_BG, R.drawable.reader_bg_black);
                //发送广播
                intent.putExtra(ReaderActivity.SET_BG_EXTRA, R.drawable.reader_bg_black);
                break;
            case R.id.ivBgblue:
                bgBlueChecked.setVisibility(VISIBLE);
                editor.putInt(SETTING_BG, R.drawable.reader_bg_lightblue);
                //发送广播
                intent.putExtra(ReaderActivity.SET_BG_EXTRA, R.drawable.reader_bg_lightblue);
                break;
            case R.id.ivBgGreen:
                bgGreenChecked.setVisibility(View.VISIBLE);
                editor.putInt(SETTING_BG, R.drawable.reader_bg_lightgreen);
                //发送广播
                intent.putExtra(ReaderActivity.SET_BG_EXTRA, R.drawable.reader_bg_lightgreen);
                break;
            case R.id.ivBgYellow:
                bgYellowChecked.setVisibility(VISIBLE);
                editor.putInt(SETTING_BG, R.drawable.reader_bg_yellow);
                //发送广播
                intent.putExtra(ReaderActivity.SET_BG_EXTRA, R.drawable.reader_bg_yellow);
                break;
            case R.id.ivBgWhite:
                bgWhiteChecked.setVisibility(View.VISIBLE);
                editor.putInt(SETTING_BG, R.drawable.reader_bg_white);
                //发送广播
                intent.putExtra(ReaderActivity.SET_BG_EXTRA, R.drawable.reader_bg_white);
                break;
            default:
                bgYellowChecked.setVisibility(VISIBLE);
                editor.putInt(SETTING_BG, R.drawable.reader_bg_yellow);
                //发送广播
                intent.putExtra(ReaderActivity.SET_BG_EXTRA, R.drawable.reader_bg_yellow);
                break;
        }
        mActivity.sendBroadcast(intent);
        editor.apply();
    }


    /**
     * 设置监听器,减小字体大小
     */

    @OnClick(R.id.btFontDec)
    public void decFontSize() {
        int currentSize = Integer.parseInt(tvFontSize.getText().toString());
        currentSize -= 2;
        tvFontSize.setText(String.format(Locale.CHINA, "%d", currentSize));
        if (editor == null) {
            editor = preference.edit();
        }
        editor.putInt(SETTING_FONTSIZE, currentSize);
        editor.apply();
        //发送消息
        getCurrentActivity();
        Intent intent = new Intent();
        intent.setAction(ReaderActivity.SET_FONT_SIZE);
        intent.putExtra(ReaderActivity.SET_FONT_EXTRA, currentSize);
        mActivity.sendBroadcast(intent);
    }

    @OnClick(R.id.btFontInc)
    public void IncFontSize() {
        int currentSize = Integer.parseInt(tvFontSize.getText().toString());
        currentSize += 2;
        if (editor == null) {
            editor = preference.edit();
        }
        editor.putInt(SETTING_FONTSIZE, currentSize);
        editor.apply();
        tvFontSize.setText(String.format(Locale.CHINA, "%d", currentSize));
        //发送消息
        getCurrentActivity();
        Intent intent = new Intent();
        intent.setAction(ReaderActivity.SET_FONT_SIZE);
        intent.putExtra(ReaderActivity.SET_FONT_EXTRA, currentSize);
        mActivity.sendBroadcast(intent);
    }


    /**
     * 作用：为系统亮度按钮设置监听器
     */

    @OnClick(R.id.rbSysBrightness)
    public void sysBrightness(View view) {
        //判断当前view的Checked状态
        RadioButton radioButton = (RadioButton) view;
        if (radioButton.isChecked()) {
            radioButton.setChecked(false);
        } else {
            radioButton.setChecked(true);
            //设置系统亮度
            boolean isAutoBrightness = preference.getBoolean(SETTING_LAST_BRIGHTNESS, false);
            if (isAutoBrightness) {
                Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
            } else {
                int lastBright = preference.getInt(SETTING_LAST_BRIGHTNESS, -1);
                if (lastBright != -1) {
                    Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, lastBright);
                }
            }
        }
    }


    /**
     * 作用：判断当前设备的亮度调节模式
     */

    private boolean isAutoBrightness() throws Settings.SettingNotFoundException {

        return Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE)
                == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
    }


    /**
     * 为下方的背景选择按钮设置监听器
     */

    @OnClick({R.id.ivBgWhite, R.id.ivBgGreen, R.id.ivBgBlack, R.id.ivBgYellow, R.id.ivBgblue})
    public void chooseBg(View view) {
        checkSpcBg((ImageView) view);
    }


    /**
     * 作用：调整屏幕亮度方法
     *
     * @param brightness 亮度值 取值范围 0-255
     */


    private void setBrightness(int brightness) {
        ContentResolver cr = context.getContentResolver();
        try {
            if (isAutoBrightness()) {
                //将亮度设置调整为手动设置
                Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE,
                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
            //设置成为指定的亮度
            Settings.System.putFloat(cr, Settings.System.SCREEN_BRIGHTNESS, brightness);
            if (editor == null) {
                editor = preference.edit();
            }
            editor.putInt(SETTING_BRIGHTNESS, brightness);
            editor.apply();
        } catch (Settings.SettingNotFoundException e) {
            getCurrentActivity();
            Intent intent = new Intent();
            intent.setAction(ReaderActivity.SET_BRIGHTNESS_FAIL);
            mActivity.sendBroadcast(intent);
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        //将系统亮度按钮设置为unchecked状态
        rbSysBrightness.setChecked(false);
        setBrightness(progress);

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {


    }

    /**
     * 判断并且获取Activity的方法
     */


    private void getCurrentActivity() {
        if (mActivity == null && context instanceof Activity) {
            mActivity = (Activity) context;
        }
    }

    @OnClick(R.id.btFont)
    public void openFontActivity() {
        getCurrentActivity();
        Intent intent = new Intent(mActivity, FontActivity.class);
        intent.putExtra("fontFamily", fontFamily);
        mActivity.startActivityForResult(intent, FONT_REQUEST_CODE);
    }
}
